<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>代码生成管理</title>
    <div th:replace="common/base"></div>
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">

        <div style="margin: 0px 10px">
            <form class="layui-form layui-form-pane" action="">
                <div class="layui-form-item" style="margin: 0px">
                    <div class="layui-inline">
                        <label class="layui-form-label">表名</label>
                        <div class="layui-input-inline">
                            <input type="text" name="tableName" autocomplete="off" class="layui-input"
                                   placeholder="请输入数据库表名">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <button id="btnSearch" type="submit" class="layui-btn layui-btn-primary" lay-submit
                                lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索
                        </button>
                    </div>
                </div>
            </form>
        </div>

        <script type="text/html" id="toolbarGenerator">
            <div class="layui-btn-container">

            </div>
        </script>

        <table id="generatorTable" lay-filter="generatorTable"></table>

        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-primary layui-btn-xs data-count-preview" lay-event="preview">预览</a>
            <a class="layui-btn layui-btn-primary layui-btn-xs data-count-download" lay-event="download">下载</a>
            <a class="layui-btn layui-btn-primary layui-btn-xs data-count-config" lay-event="config">配置</a>
            <a class="layui-btn layui-btn-primary layui-btn-xs data-count-gen" lay-event="gen">生成</a>
        </script>
    </div>
</div>
<!-- 表单预览弹窗 -->
<script type="text/html" id="previewDialog">
    <div class="layui-tab layui-tab-brief">
        <ul class="layui-tab-title" id="previewTabTitle">

        </ul>
        <div class="layui-tab-content" id="previewTabContent">

        </div>
    </div>
</script>

<div th:replace="common/baseJS"></div>
<script th:inline="none">
    layui.use(['form', 'table', 'ab'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table,
            ab = layui.ab;

        table.render({
            elem: '#generatorTable',
            url: '/code/generator/tables',
            toolbar: '#toolbarGenerator',
            defaultToolbar: ['filter', 'exports', 'print'],
            cols: [[
                {type: "checkbox", width: 50},
                {field: 'id', width: 80, title: 'ID', hide: true},
                {field: 'tableName', title: '表名'},
                {field: 'engine', title: '数据库引擎'},
                {field: 'coding', title: '字符编码集'},
                {field: 'remark', title: '备注'},
                {
                    field: 'createTime', width: 180, title: '创建时间', templet: function (d) {
                        if (d.createTime) {
                            return ab.dateUtil.format(d.createTime, "yyyy-MM-dd hh:mm:ss")
                        } else {
                            return ''
                        }
                    }
                },
                {title: '操作', width: 220, toolbar: '#currentTableBar', align: "center"}
            ]],
            response: {
                statusName: 'status', //规定数据状态的字段名称，默认：code
                statusCode: 200, //规定成功的状态码，默认：0
                msgName: 'hint', //规定状态信息的字段名称，默认：msg
                countName: 'total', //规定数据总数的字段名称，默认：count
                dataName: 'rows' //规定数据列表的字段名称，默认：data
            },
            limits: [10, 15, 20, 25, 50, 100],
            limit: 15,
            page: true,
            skin: 'line'
        });


        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            //执行搜索重载
            table.reload('generatorTable', {
                page: {curr: 1},
                where: data.field
            }, 'data');

            return false;
        });
        //自定义验证规则
        form.verify({
            // name: function (value) {
            //     if (value.length < 2) {
            //         return '模块名称至少得2个字符啊';
            //     }
            // }
        });

        /* 表格头工具栏点击事件 */
        table.on('toolbar(generatorTable)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作
                showConfigModel();
            } else if (obj.event === 'delete') {  // 监听删除操作
                var checkStatus = table.checkStatus('generatorTable')
                    , data = checkStatus.data;
                if (data.length == 0) {
                    ab.window.msg("请至少选择一条数据！", "error");
                    return;
                }
                var ids = [];
                for (var i = 0; i < data.length; i++) {
                    ids.push(data[i].id);
                }
                ab.util.deleteForm({
                    url: "/code/generator",// 请求地址
                    type: "delete",// 请求提交方式
                    data: JSON.stringify(ids),// 发送回去的数据 JSON.stringify(data)
                    success: function (data) {
                        $("#btnSearch").click();
                    }
                });
            }
        });

        /* 表格操作列点击事件 */
        table.on('tool(generatorTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'preview') {
                showPreviewModel(data);
            } else if (obj.event === 'download') {
                download(data);
            } else if (obj.event === 'config') {
                showConfigModel(data);
            } else if (obj.event === 'gen') {
                gen(data);
            }
        });

        //监听表格复选框选择
        table.on('checkbox(generatorTable)', function (obj) {
            // console.log(obj)
        });

        $('#component-tabs .site-demo-active').on('click', function () {
            var othis = $(this), type = othis.data('type');
            active[type] ? active[type].call(this, othis) : '';
        });

        /* 预览代码 */
        function showPreviewModel(mData) {
            var configIdx = ab.window.open({
                id: "configGenerator",
                title: '代码预览__表名：' + mData.tableName,
                content: '/code/generator/preview?tableName=' + mData.tableName,
                type: 2,
                offset: 0,
                area: ['100%', '100%']
            });
            $(window).on("resize", function () {
                layer.full(configIdx);
            });
        }

        /* 显示配置弹窗 */
        function showConfigModel(mData) {
            var configIdx = ab.window.open({
                id: "configGenerator",
                title: '生成配置__表名：' + mData.tableName,
                content: '/code/generator/config?tableName=' + mData.tableName,
                type: 2,
                offset: 0,
                area: ['100%', '100%']
            });
            $(window).on("resize", function () {
                layer.full(configIdx);
            });
        }

        /* 打包下载 */
        function download(mData) {
            postDownloadFile("/code/generator/" + mData.tableName + "/2", {}, function (data) {
                downloadFile(data, mData.tableName, "zip");
            })
        }

        /* 生成代码 */
        function gen(mData) {
            var loadingIdx = layer.load(2);
            $.ajax({
                url: "/code/generator/" + mData.tableName+"/0",// 请求地址
                type: "post",// 请求提交方式
                data: {},
                xhrFields:{ responseType: "blob" },//arraybuffer
                success: function (data) {
                    ab.window.msg("生成成功","success");
                    layer.close(loadingIdx)
                },
                error:function () {
                    layer.close(loadingIdx)
                }
            });
        }

        function postDownloadFile(url, data, callback) {
            var param = null;
            if (data) {
                param = JSON.stringify(data);
            }
            var request = new XMLHttpRequest();

            request.open('POST', url + "?timeStamp=" + new Date().getTime(), true);
            request.responseType = 'arraybuffer'
            request.setRequestHeader('Cache-Control', 'no-cache');
            request.setRequestHeader("Content-type", "application/json");
            request.onreadystatechange = function (res) {
                if (request.readyState == 4) {
                    if (request.status == 200) {
                        if (typeof callback === "function") {
                            callback(request.response)
                        }
                    }
                }
            }
            request.send(param);
        }

        // 下载文件
        function downloadFile(obj, name, suffix) {
            var url = window.URL.createObjectURL(new Blob([obj]))
            var link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            var fileName = name + '_' + (new Date()).getTime() + '.' + suffix
            link.setAttribute('download', fileName)
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
        }
    });
</script>

</body>
</html>